/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.techshop.controller;

import com.techshop.model.Category;
import com.techshop.model.Color;
import com.techshop.model.Image;
import com.techshop.model.Manufacturer;
import com.techshop.model.Os;
import com.techshop.model.Phone;
import com.techshop.model.PhoneCode;
import com.techshop.service.CategoryService;
import com.techshop.service.ImageService;
import com.techshop.service.ManufacturerService;
import com.techshop.service.OsService;
import com.techshop.service.PhoneCodeService;
import com.techshop.service.PhoneService;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;

/**
 *
 * @author Hai-PC
 */
@ManagedBean(name = "phoneController")
@ViewScoped
public class PhoneController extends AbstractController
{
    Phone selectedPhone;
    Color selectedColor;
    Image selectedImage;
    private List<Phone> phoneList;
    List<Category> categoryList;
    List<Manufacturer> manufacturerList;
    List<PhoneCode> phoneCodeList;
    List<Image> image360List;
    List<Image> imageSlideList;
    List<Image> imageGalleryList;
    List<Image> imageFuncList;
    List<Image> imageKitList;
    List<Image> imageSpecList;
    List<Os> osList;
    List<Phone> filterPhones;
    
    @ManagedProperty(value = "#{phoneService}")
    PhoneService phoneService;
    @ManagedProperty(value = "#{categoryService}")
    CategoryService categoryService;
    @ManagedProperty(value = "#{manufacturerService}")
    ManufacturerService manufacturerService;
    @ManagedProperty(value = "#{phoneCodeService}")
    PhoneCodeService phoneCodeService;
    @ManagedProperty(value = "#{osService}")
    OsService osService;
    @ManagedProperty(value = "#{imageService}")
    ImageService imageService;    

    boolean isSearch = false;
    int num_slide = 0;
    int num_gallery = 0;
    
    @PostConstruct
    public void init()
    {
        resetSelectedPhone();
    }
    
    public void insert()
    {
        isSearch = false;
        if (getPhoneService().insert(selectedPhone))
        {
            addInfoMessage("Thêm thành công");
            resetSelectedPhone();
        }
        else
        {
            addErrorMessage("Thêm thất bại");
        }
    }

    public void update()
    {
        isSearch = false;
        if (getPhoneService().update(selectedPhone))
        {
            addInfoMessage("Cập nhật thành công");
        }
        else
        {
            addErrorMessage("Cập nhật thất bại");
        }
    }
    
    public void delete()
    {
        isSearch = false;
        if (getPhoneService().delete(selectedPhone))
        {
            addInfoMessage("Xóa thành công");
        }
        else
        {
            addErrorMessage("Xóa thất bại");
        }
    }
    
    public void deleteImage()
    {
        if (imageService.delete(selectedImage))
        {
            ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
            File result = new File(extContext.getRealPath(selectedImage.getLink()));
            if (result.delete())
            {
                addInfoMessage("Xóa thành công");
            }
        }
        else
        {
            addErrorMessage("Xóa thất bại");
        }
    }
    
    public void resetSelectedPhone()
    {
        selectedPhone = new Phone();
        selectedColor = new Color();
        selectedPhone.setCategory(new Category());
        selectedPhone.setManufacturer(new Manufacturer());
        selectedPhone.setOs(new Os());
    }
    
    public List<Phone> getPhoneList()
    {
        if (!isSearch)
        {
            setPhoneList(phoneService.getAll());
        }
        return phoneList;
    }

    public void setPhoneList(List<Phone> phoneList)
    {
        this.phoneList = phoneList;
    }
    
    /**
     * @return the categoryList
     */
    public List<Category> getCategoryList()
    {
        return getCategoryService().findAll();
    }

    /**
     * @param categoryList the categoryList to set
     */
    public void setCategoryList(List<Category> categoryList)
    {
        this.categoryList = categoryList;
    }
    
    /**
     * @return the manufacturerList
     */
    public List<Manufacturer> getManufacturerList()
    {
        return getManufacturerService().findAll();
    }

    /**
     * @param manufacturerList the manufacturerList to set
     */
    public void setManufacturerList(List<Manufacturer> manufacturerList)
    {
        this.manufacturerList = manufacturerList;
    }

    public PhoneService getPhoneService()
    {
        return phoneService;
    }

    public void setPhoneService(PhoneService phoneService)
    {
        this.phoneService = phoneService;
    }
    
    /**
     * @return the categoryService
     */
    public CategoryService getCategoryService()
    {
        return categoryService;
    }

    /**
     * @param categoryService the categoryService to set
     */
    public void setCategoryService(CategoryService categoryService)
    {
        this.categoryService = categoryService;
    }
    
    /**
     * @return the manufacturerService
     */
    public ManufacturerService getManufacturerService()
    {
        return manufacturerService;
    }

    /**
     * @param manufacturerService the manufacturerService to set
     */
    public void setManufacturerService(ManufacturerService manufacturerService)
    {
        this.manufacturerService = manufacturerService;
    }
    
    /**
     * @return the selectedPhone
     */
    public Phone getSelectedPhone()
    {
        return selectedPhone;
    }

    /**
     * @param selectedPhone the selectedPhone to set
     */
    public void setSelectedPhone(Phone selectedPhone)
    {
        this.selectedPhone = selectedPhone;
    }

    /**
     * @return the filterPhones
     */
    public List<Phone> getFilterPhones()
    {
        return filterPhones;
    }

    /**
     * @param filterPhones the filterPhones to set
     */
    public void setFilterPhones(List<Phone> filterPhones)
    {
        this.filterPhones = filterPhones;
    }
    
    public synchronized void handleFileUpload360(FileUploadEvent event) throws IOException
    {
        //Primitives
        final int BUFFER_SIZE = 6124;
        ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
        // Get categoryId
        String categoryId = phoneService.getById(selectedPhone.getId()).getCategory().getId().toString();
        String folderToUpload = "//resources//images//product//" + categoryId + "//" + selectedPhone.getId() + "//360//";
        (new File(extContext.getRealPath(folderToUpload))).mkdirs();       

        
        String filePath = folderToUpload + event.getFile().getFileName();
        File result = new File(extContext.getRealPath(filePath));
        System.out.println(extContext.getRealPath(filePath));

        try
        {
            InputStream inputStream;
            try (FileOutputStream fileOutputStream = new FileOutputStream(result))
            {
                byte[] buffer = new byte[BUFFER_SIZE];
                int bulk;
                inputStream = event.getFile().getInputstream();
                while (true)
                {
                    bulk = inputStream.read(buffer);
                    if (bulk < 0)
                    {
                        break;
                    }
                    fileOutputStream.write(buffer, 0, bulk);
                    fileOutputStream.flush();
                }
            }
            inputStream.close();

            addInfoMessage("file name: " + event.getFile().getFileName() + 
                    "file size: " + event.getFile().getSize() / 1024 + " Kb content type: " + 
                    event.getFile().getContentType() + "The file was uploaded.");
            
            filePath = "//resources//images//product//" + categoryId + "//" + selectedPhone.getId() + "//360//" + event.getFile().getFileName();
            Image image = new Image(selectedPhone, filePath, "360");
            imageService.insert(image);
        }
        catch (IOException e)
        {
            System.out.printf("Error :", e.toString());
            addErrorMessage("The files were not uploaded!");
        }
    }
    
    public void handleFileUploadSlide(FileUploadEvent event) throws IOException
    {
        //Primitives
        final int BUFFER_SIZE = 6124;
        ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
        // Get categoryId
        String categoryId = phoneService.getById(selectedPhone.getId()).getCategory().getId().toString();
        String folderToUpload = "//resources//images//product//" + categoryId + "//" + selectedPhone.getId() + "//slide//";
        (new File(extContext.getRealPath(folderToUpload))).mkdirs();       

        
        String filePath = folderToUpload + event.getFile().getFileName();
        File result = new File(extContext.getRealPath(filePath));
        System.out.println(extContext.getRealPath(filePath));

        try
        {
            InputStream inputStream;
            try (FileOutputStream fileOutputStream = new FileOutputStream(result))
            {
                byte[] buffer = new byte[BUFFER_SIZE];
                int bulk;
                inputStream = event.getFile().getInputstream();
                while (true)
                {
                    bulk = inputStream.read(buffer);
                    if (bulk < 0)
                    {
                        break;
                    }
                    fileOutputStream.write(buffer, 0, bulk);
                    fileOutputStream.flush();
                }
            }
            inputStream.close();

            addInfoMessage("file name: " + event.getFile().getFileName() + 
                    "file size: " + event.getFile().getSize() / 1024 + " Kb content type: " + 
                    event.getFile().getContentType() + "The file was uploaded.");
            
            filePath = "//resources//images//product//" + categoryId + "//" + selectedPhone.getId() + "//slide//" + event.getFile().getFileName();
            Image image = new Image(selectedPhone, filePath, "slide");
            imageService.insert(image);
            
            num_slide++;
        }
        catch (IOException e)
        {
            System.out.printf("Error :", e.toString());
            addErrorMessage("The files were not uploaded!");
        }
    }
    
    public void updateNumSlide()
    {
        System.out.println(num_slide);
        phoneService.updateNumSlide(selectedPhone.getId(), num_slide);
    }
    
    public void updateNumGallery()
    {
        PhoneCode phoneCode = phoneCodeService.getByPhoneAndColor(selectedPhone.getId(), selectedColor.getId());
        phoneCode.setNumPhoto(num_gallery + phoneCode.getNumPhoto());
        phoneCodeService.update(phoneCode);
    }
    
    public void handleFileUploadGallery(FileUploadEvent event) throws IOException
    {
        //Primitives
        final int BUFFER_SIZE = 6124;
        ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
        // Get categoryId
        String categoryId = phoneService.getById(selectedPhone.getId()).getCategory().getId().toString();
        // Get phoneCodeId
        String phoneCodeId = phoneCodeService.getByPhoneAndColor(selectedPhone.getId(), selectedColor.getId()).getId().toString();
        String folderToUpload = "//resources//images//product//" + categoryId + "//" + selectedPhone.getId() + "//gallery//" + phoneCodeId + "//";
        (new File(extContext.getRealPath(folderToUpload))).mkdirs();       

        
        String filePath = folderToUpload + event.getFile().getFileName();
        File result = new File(extContext.getRealPath(filePath));
        System.out.println(extContext.getRealPath(filePath));

        try
        {
            InputStream inputStream;
            try (FileOutputStream fileOutputStream = new FileOutputStream(result))
            {
                byte[] buffer = new byte[BUFFER_SIZE];
                int bulk;
                inputStream = event.getFile().getInputstream();
                while (true)
                {
                    bulk = inputStream.read(buffer);
                    if (bulk < 0)
                    {
                        break;
                    }
                    fileOutputStream.write(buffer, 0, bulk);
                    fileOutputStream.flush();
                }
            }
            inputStream.close();

            addInfoMessage("file name: " + event.getFile().getFileName() + 
                    "file size: " + event.getFile().getSize() / 1024 + " Kb content type: " + 
                    event.getFile().getContentType() + "The file was uploaded.");
            
            filePath = "//resources//images//product//" + categoryId + "//" + selectedPhone.getId() + "//gallery//" + phoneCodeId + "//" + event.getFile().getFileName();
            Image image = new Image(selectedPhone, selectedColor, filePath, "gallery");
            imageService.insert(image);
        }
        catch (IOException e)
        {
            System.out.printf("Error :", e.toString());
            addErrorMessage("The files were not uploaded!");
        }
    }
    
    public void handleFileUploadFunc(FileUploadEvent event) throws IOException
    {
        //Primitives
        final int BUFFER_SIZE = 6124;
        ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
        // Get categoryId
        String categoryId = phoneService.getById(selectedPhone.getId()).getCategory().getId().toString();
        String folderToUpload = "//resources//images//product//" + categoryId + "//" + selectedPhone.getId() + "//";
        (new File(extContext.getRealPath(folderToUpload))).mkdirs();       

        
        String filePath = folderToUpload + event.getFile().getFileName();
        File result = new File(extContext.getRealPath(filePath));
        System.out.println(extContext.getRealPath(filePath));

        try
        {
            InputStream inputStream;
            try (FileOutputStream fileOutputStream = new FileOutputStream(result))
            {
                byte[] buffer = new byte[BUFFER_SIZE];
                int bulk;
                inputStream = event.getFile().getInputstream();
                while (true)
                {
                    bulk = inputStream.read(buffer);
                    if (bulk < 0)
                    {
                        break;
                    }
                    fileOutputStream.write(buffer, 0, bulk);
                    fileOutputStream.flush();
                }
            }
            inputStream.close();

            addInfoMessage("file name: " + event.getFile().getFileName() + 
                    "file size: " + event.getFile().getSize() / 1024 + " Kb content type: " + 
                    event.getFile().getContentType() + "The file was uploaded.");
            
            filePath = "//resources//images//product//" + categoryId + "//" + selectedPhone.getId() + "//" + event.getFile().getFileName();
            Image image = new Image(selectedPhone, filePath, "func");
            imageService.insert(image);
        }
        catch (IOException e)
        {
            System.out.printf("Error :", e.toString());
            addErrorMessage("The files were not uploaded!");
        }
    }
    
    public void handleFileUploadKit(FileUploadEvent event) throws IOException
    {
        //Primitives
        final int BUFFER_SIZE = 6124;
        ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
        // Get categoryId
        String categoryId = phoneService.getById(selectedPhone.getId()).getCategory().getId().toString();
        String folderToUpload = "//resources//images//product//" + categoryId + "//" + selectedPhone.getId() + "//";
        (new File(extContext.getRealPath(folderToUpload))).mkdirs();       

        
        String filePath = folderToUpload + event.getFile().getFileName();
        File result = new File(extContext.getRealPath(filePath));
        System.out.println(extContext.getRealPath(filePath));

        try
        {
            InputStream inputStream;
            try (FileOutputStream fileOutputStream = new FileOutputStream(result))
            {
                byte[] buffer = new byte[BUFFER_SIZE];
                int bulk;
                inputStream = event.getFile().getInputstream();
                while (true)
                {
                    bulk = inputStream.read(buffer);
                    if (bulk < 0)
                    {
                        break;
                    }
                    fileOutputStream.write(buffer, 0, bulk);
                    fileOutputStream.flush();
                }
            }
            inputStream.close();

            addInfoMessage("file name: " + event.getFile().getFileName() + 
                    "file size: " + event.getFile().getSize() / 1024 + " Kb content type: " + 
                    event.getFile().getContentType() + "The file was uploaded.");
            
            filePath = "//resources//images//product//" + categoryId + "//" + selectedPhone.getId() + "//" + event.getFile().getFileName();
            Image image = new Image(selectedPhone, filePath, "kit");
            imageService.insert(image);
        }
        catch (IOException e)
        {
            System.out.printf("Error :", e.toString());
            addErrorMessage("The files were not uploaded!");
        }
    }

    public void handleFileUploadSpec(FileUploadEvent event) throws IOException
    {
        //Primitives
        final int BUFFER_SIZE = 6124;
        ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
        // Get categoryId
        String categoryId = phoneService.getById(selectedPhone.getId()).getCategory().getId().toString();
        String folderToUpload = "//resources//images//product//" + categoryId + "//" + selectedPhone.getId() + "//";
        (new File(extContext.getRealPath(folderToUpload))).mkdirs();       

        
        String filePath = folderToUpload + event.getFile().getFileName();
        File result = new File(extContext.getRealPath(filePath));
        System.out.println(extContext.getRealPath(filePath));

        try
        {
            InputStream inputStream;
            try (FileOutputStream fileOutputStream = new FileOutputStream(result))
            {
                byte[] buffer = new byte[BUFFER_SIZE];
                int bulk;
                inputStream = event.getFile().getInputstream();
                while (true)
                {
                    bulk = inputStream.read(buffer);
                    if (bulk < 0)
                    {
                        break;
                    }
                    fileOutputStream.write(buffer, 0, bulk);
                    fileOutputStream.flush();
                }
            }
            inputStream.close();

            addInfoMessage("file name: " + event.getFile().getFileName() + 
                    "file size: " + event.getFile().getSize() / 1024 + " Kb content type: " + 
                    event.getFile().getContentType() + "The file was uploaded.");
            
            filePath = "//resources//images//product//" + categoryId + "//" + selectedPhone.getId() + "//" + event.getFile().getFileName();
            Image image = new Image(selectedPhone, filePath, "spec");
            imageService.insert(image);
        }
        catch (IOException e)
        {
            System.out.printf("Error :", e.toString());
            addErrorMessage("The files were not uploaded!");
        }
    }
    
    public List<Os> getOsList() {
        setOsList(osService.getAll());
        return osList;
    }

    public void setOsList(List<Os> osList) {
        this.osList = osList;
    }

    public OsService getOsService() {
        return osService;
    }

    public void setOsService(OsService osService) {
        this.osService = osService;
    }

    public Color getSelectedColor() {
        return selectedColor;
    }

    public void setSelectedColor(Color selectedColor) {
        this.selectedColor = selectedColor;
    }

    public List<PhoneCode> getPhoneCodeList() {
        try
        {
            setPhoneCodeList(phoneCodeService.getByPhoneId(selectedPhone.getId()));
        }
        catch (NullPointerException e)
        {
        }
        return phoneCodeList;
    }

    public void setPhoneCodeList(List<PhoneCode> phoneCodeList) {
        
        this.phoneCodeList = phoneCodeList;
    }

    public PhoneCodeService getPhoneCodeService() {
        return phoneCodeService;
    }

    public void setPhoneCodeService(PhoneCodeService phoneCodeService) {
        this.phoneCodeService = phoneCodeService;
    }
    
    public void test()
    {
        System.out.println(selectedColor.getId());
    }

    public ImageService getImageService() {
        return imageService;
    }

    public void setImageService(ImageService imageService) {
        this.imageService = imageService;
    }

    public List<Image> getImage360List() {
        try
        {
            setImage360List(imageService.getByPhone(selectedPhone.getId(), "360"));
        }
        catch (NullPointerException e)
        {
        }
        return image360List;
    }

    public void setImage360List(List<Image> image360List) {
        this.image360List = image360List;
    }

    public List<Image> getImageSlideList() {
        try
        {
            setImageSlideList(imageService.getByPhone(selectedPhone.getId(), "slide"));
        }
        catch (NullPointerException e)
        {
        }
        return imageSlideList;
    }

    public void setImageSlideList(List<Image> imageSlideList) {
        this.imageSlideList = imageSlideList;
    }

    public List<Image> getImageGalleryList() {
        try
        {
            setImageGalleryList(imageService.getByPhoneAndColor(selectedPhone.getId(), selectedColor.getId(), "gallery"));
        }
        catch (NullPointerException e)
        {
        }
        return imageGalleryList;
    }

    public void setImageGalleryList(List<Image> imageGalleryList) {
        this.imageGalleryList = imageGalleryList;
    }

    public List<Image> getImageFuncList() {
        try
        {
            setImageFuncList(imageService.getByPhone(selectedPhone.getId(), "func"));
        }
        catch (NullPointerException e)
        {
        }
        return imageFuncList;
    }

    public void setImageFuncList(List<Image> imageFuncList) {
        this.imageFuncList = imageFuncList;
    }

    public List<Image> getImageKitList() {
        try
        {
            setImageKitList(imageService.getByPhone(selectedPhone.getId(), "kit"));
        }
        catch (NullPointerException e)
        {
        }
        return imageKitList;
    }

    public void setImageKitList(List<Image> imageKitList) {
        this.imageKitList = imageKitList;
    }

    public List<Image> getImageSpecList() {
        try
        {
            setImageSpecList(imageService.getByPhone(selectedPhone.getId(), "spec"));
        }
        catch (NullPointerException e)
        {
        }
        return imageSpecList;
    }

    public void setImageSpecList(List<Image> imageSpecList) {
        this.imageSpecList = imageSpecList;
    }

    public Image getSelectedImage() {
        return selectedImage;
    }

    public void setSelectedImage(Image selectedImage) {
        this.selectedImage = selectedImage;
    }
    
    public void search()
    {
        isSearch = true;
        setPhoneList(phoneService.search(selectedPhone.getName(), selectedPhone.getCategory().getId(), selectedPhone.getManufacturer().getId()));
    }
}